package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket=socket;
    }
    public void run(){
        try {
        //1解析请求
        HttpServletRequest request = new HttpServletRequest(socket);
        //2处理请求
        String path = request.getUri();//获取路径
        System.out.println(path);
        File baseDir = new File(
                ClientHandler.class.getClassLoader().getResource(".").toURI()
        );
        File staticDir = new File(baseDir,"static");
        File file = new File(staticDir,path);
        int statusCode;
        String statusReason;

        if(file.isFile()){
            statusCode=200;
            statusReason="OK";
        }else{
            statusCode=404;
            statusReason="NotFound";
            file = new File(staticDir,"/404.html");
        }

        //发送状态头
        println("HTTP/1.1"+" "+statusCode+" "+statusReason);
        //发送响应头
        println("Content-Type: text/html");
        println("Content-Length: "+file.length());
        //单独发送回车+换行
        println("");
        //发送正文

            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[1024*10];
            int len;
            while((len=fis.read(data))!=-1){
                out.write(data,0,len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.UTF_8));
        out.write(13);
        out.write(10);
    }


}
